package com.shwread.android.ui.page.chat.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.PhoneNumberUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciko.code.logic.bean.AddressBookInfo;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw.activity.ChatPersonalInfoActivity;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.dialog.ContactCallSelectDialog;
import com.shwread.android.ui.page.chat.ContactsPage;
import com.shwread.android.ui.widget.CircleImageView;
import com.squareup.picasso.Picasso;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.ContactInfo;
import logic.bean.GroupBean;
import logic.constants.Const;
import logic.util.Util;
import logic.util.Utils;
import logic.util.logutil.LogUtil;


/**
 * 群分组数据适配器
 *
 * @author Jayden
 */
@SuppressLint ("ResourceAsColor")
public class ContactGroupAdapter
        extends
        BaseExpandableListAdapter
{

	private final Context                          context;

	private List<GroupBean>                        mGroupData;

	private HashMap<String, List<AddressBookInfo>> mChildData;

	private LayoutInflater                         mInflater;
	private ExpandableListView                     lvContacts;

	private ContactCallSelectDialog                selectNum;

	public ContactGroupAdapter(Context context, ExpandableListView lvContacts, List<GroupBean> mGroupData, HashMap<String, List<AddressBookInfo>> mChildData) {
		this.context = context;
		this.lvContacts = lvContacts;
		this.mChildData = mChildData;
		this.mGroupData = mGroupData;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getGroupCount() {
		return null != mGroupData ? mGroupData.size() : 0;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		if (null == mChildData || null == mGroupData || mGroupData.size() == 0 || null == mGroupData.get(groupPosition) || null == mChildData.get(mGroupData.get(groupPosition).getName()))
		{
			return 0;
		}
		else
		{
			return mChildData.get(mGroupData.get(groupPosition).getName()).size();
		}
	}

	@Override
	public Object getGroup(int groupPosition) {
		return mGroupData.get(groupPosition);
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		if (null == mChildData || null == mGroupData || mGroupData.size() == 0 || null == mGroupData.get(groupPosition) || null == mChildData.get(mGroupData.get(groupPosition).getName()))
		{
			return null;
		}
		else
		{
			return mChildData.get(mGroupData.get(groupPosition).getName()).get(childPosition);
		}
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		View v;
		if (convertView == null)
		{
			v = mInflater.inflate(isExpanded ? R.layout.chat_group_item : R.layout.chat_group_item, parent, false);
		}
		else
		{
			v = convertView;
		}

		final GroupBean group = mGroupData.get(groupPosition);
		TextView groupNameTV = (TextView) v.findViewById(R.id.item_expandable_group);
		final ImageView openIV = (ImageView) v.findViewById(R.id.item_img_open);
		LinearLayout llGroup = (LinearLayout) v.findViewById(R.id.ll_item_group);
		groupNameTV.setText(group.getName());
		if (ContactsPage.isClose[groupPosition] == 0)
		{
			openIV.setImageResource(R.drawable.change_store_icon);
		}
		else
		{
			openIV.setImageResource(R.drawable.change_store_icon_up);
		}
		llGroup.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v) {
				if (ContactsPage.isClose[groupPosition] != 0)
				{
					lvContacts.collapseGroup(groupPosition);
					//					openIV.setBackgroundResource(R.drawable.change_store_icon);
					openIV.setImageResource(R.drawable.change_store_icon);
					ContactsPage.isClose[groupPosition] = 0;
				}
				else
				{
					for (int i = 0; i < mGroupData.size(); i++)
					{
						if (ContactsPage.isClose[i] == 1)
						{
							lvContacts.collapseGroup(i);
							ContactsPage.isClose[i] = 0;
						}
					}
					lvContacts.expandGroup(groupPosition);
					//					openIV.setBackgroundResource(R.drawable.change_store_icon_up);
					openIV.setImageResource(R.drawable.change_store_icon_up);
					ContactsPage.isClose[groupPosition] = 1;
				}
			}
		});
		return v;
	}

	@Override
	public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
		View view;
		if (convertView == null)
		{
			view = mInflater.inflate(isLastChild ? R.layout.chat_contact_item : R.layout.chat_contact_item, parent, false);
		}
		else
		{
			view = convertView;
		}
		final AddressBookInfo contactItem = (AddressBookInfo) getChild(groupPosition, childPosition);
		CircleImageView contactsHeadImg = (CircleImageView) view.findViewById(R.id.iv_chat_head_img);
		ImageView contactsHeader = (ImageView) view.findViewById(R.id.iv_chat_contact_icon_header);
		ImageView contactsCall = (ImageView) view.findViewById(R.id.iv_chat_contact_icon_call);
		ImageView contactsMsg = (ImageView) view.findViewById(R.id.iv_chat_contact_icon_msg);
		ImageView contactsChat = (ImageView) view.findViewById(R.id.iv_chat_contact_icon_chat);
		contactsChat.setTag(childPosition);
		TextView contactsName = (TextView) view.findViewById(R.id.tv_chat_contact_name);
		RelativeLayout rlItem = (RelativeLayout) view.findViewById(R.id.rl_contact_item);
		if (Utils.isNotEmpty(contactItem.getUserHead()))
		{
			//			ImageUtil.loadLocalUrl(contactItem.getUserHead(), contactsHeadImg);
			Picasso.with(context).load(contactItem.getUserHead()).into(contactsHeadImg);
		}
		else
		{
			Picasso.with(context).load(R.drawable.chat_head_img).into(contactsHeadImg);
			//			contactsHeadImg.setBackgroundResource(R.drawable.chat_head_img);
		}
		if (contactItem.getGroupPosition() == 1)
		{
			Picasso.with(context).load(R.drawable.chat_contract_icon_header).into(contactsHeader);
			//			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_header);
			contactsHeader.setVisibility(View.VISIBLE);
		}
		else if (contactItem.getGroupPosition() == 2)
		{
			Picasso.with(context).load(R.drawable.chat_contract_icon_deputy_header).into(contactsHeader);
			//			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_deputy_header);
			contactsHeader.setVisibility(View.VISIBLE);
		}
		else
		{
			contactsHeader.setVisibility(View.GONE);
		}
		contactsName.setText(contactItem.getContactName());
		if (Utils.isEmpty(contactItem.getMobileNumber()))
		{
			contactsMsg.setVisibility(View.GONE);
			contactsChat.setVisibility(View.GONE);
		}
		else
		{
			contactsMsg.setVisibility(View.VISIBLE);
			contactsChat.setVisibility(View.VISIBLE);
		}
		contactsMsg.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				//				NewActionHelp.qryStaffInfoByAccIds(context, contactItem.getAccId(), new NimAccountHandler(1));
				//				Utils.showToast(context, "发送短信");
				if (Utils.isNotEmpty(contactItem.getMobileNumber()))
				{
					doSendSMSTo(contactItem.getMobileNumber(), null);
				}
			}
		});

		contactsCall.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				List<String> phoneList = new ArrayList<String>();
				if (Utils.isNotEmpty(contactItem.getMobileNumber()))
				{
					phoneList.add(contactItem.getMobileNumber());
				}
				if (Utils.isNotEmpty(contactItem.getPhoneNumber()))
				{
					phoneList.add(contactItem.getPhoneNumber());
				}
				selectNum = new ContactCallSelectDialog(context, phoneList);
				if (phoneList.size() > 1)
				{
					selectNum.show();
				}
				else
				{
					dialPhoneNumber(phoneList.get(0));
				}
				//				if (Utils.isNotEmpty(contactItem.getMobileNumber()))
				//				{
				//					dialPhoneNumber(contactItem.getMobileNumber());
				//				}
				//				else if (Utils.isNotEmpty(contactItem.getPhoneNumber()))
				//				{
				//					dialPhoneNumber(contactItem.getPhoneNumber());
				//				}
			}
		});

		contactsChat.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				int pos = (Integer) v.getTag();
				AddressBookInfo contactItem = (AddressBookInfo) getChild(groupPosition, pos);
				if(Const.UserStaffId.equals(contactItem.getUserId())){
					Util.showToast(context, "您不能与自己聊天");
					return;
				}
				ContactInfo info = new ContactInfo();
				info.setAccId(contactItem.getAccId());
				info.setAccount(contactItem.getMobileNumber());
				info.setHeadImage(contactItem.getUserHead());
				info.setStaffName(contactItem.getContactName());
				talkto(info);
			}
		});
		rlItem.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, ChatPersonalInfoActivity.class);
				intent.putExtra("contactInfo", (Serializable) contactItem);
				intent.putExtra("groupName", mGroupData.get(groupPosition).getName());
				context.startActivity(intent);
			}
		});
		return view;
	}

	/**
	 * 跳转到聊天页面
	 *
	 * @param item
	 */
	protected void talkto(Object item) {
		if (item instanceof ContactInfo)
		{
			ContactInfo info = (ContactInfo) item;
			String str;
			if (Utils.isNotEmpty(info.getStaffName()))
			{
				str = info.getStaffName();
			}
			else if (Utils.isNotEmpty(info.getNickName()))
			{
				str = info.getNickName();
			}
			else
			{
				str = info.getAccount();
			}
			//			Intent intent = new Intent();
			//			intent.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_CONTACT_MANGER);
			//			intent.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, str);
			//			P2PMessageActivity.start(getActivity(), info.getAccId(), intent);
			P2PMessageActivity.start(context, info.getAccId(), str);
			//			startActivity(new Intent(getActivity(), P2PMessageActivity.class));
		}
		else if (item instanceof Team)
		{
			Team team = (Team) item;
			TeamMessageActivity.start(context, team.getId());
		}

	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	@Override
	public boolean isEmpty() {
		return mGroupData != null ? mGroupData.isEmpty() : true;
	}

	public final void load(boolean reload) {
		if (!reload && !isEmpty()) { return; }

		LogUtil.d("fw", "load");
		//		startTask(null, false);
	}

	//	public final void query(String query) {
	//		startTask(new TextQuery(query), true);
	//	}
	//	
	//	public final void query(TextQuery query) {
	//		startTask(query, true);
	//	}
	//	public class NimAccountHandler
	//	        extends
	//	        ObjectHttpResponseHandler<TeamMemberX>
	//	{
	//		private int type = 1;
	//		
	//		public NimAccountHandler(int type) {
	//			this.type = type;
	//		}
	//		
	//		@Override
	//		public Type getType() {
	//			return new TypeToken<TeamMemberX>()
	//			{
	//			}.getType();
	//		}
	//		
	//		@Override
	//		public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
	//			// TODO Auto-generated method stub
	//			
	//		}
	//		
	//		@Override
	//		public void onSuccess(int arg0, Header[] arg1, TeamMemberX arg2, String arg3) {
	//			if (null == arg2) return;
	//			if (type == 1)
	//			{
	//				doSendSMSTo(arg2.getAccount(), "");
	//			}
	//			else
	//			{
	//				dialPhoneNumber(arg2.getAccount());
	//			}
	//		}

	//		
	//		@Override
	//		public void onSuccess(int i, Header[] headers, PersonBean personBean, String s) {
	//			if (null == personBean) return;
	//			if (type == 1)
	//			{
	//				doSendSMSTo(personBean.getmOBILE(), "");
	//			}
	//			else
	//			{
	//				dialPhoneNumber(personBean.getmOBILE());
	//			}
	//			
	//		}
	//		
	//		@Override
	//		public Type getType() {
	//			return new TypeToken<PersonBean>()
	//			{
	//			}.getType();
	//		}
	//	}

	/**
	 * 调起系统发短信功能
	 *
	 * @param phoneNumber
	 * @param message
	 */
	public void doSendSMSTo(String phoneNumber, String message) {
		if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber))
		{
			Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
			intent.putExtra("sms_body", message);
			context.startActivity(intent);
		}
	}

	/**
	 * 调起系统拨号盘
	 *
	 * @param phoneNumber
	 */
	public void dialPhoneNumber(String phoneNumber) {
		Intent intent = new Intent(Intent.ACTION_DIAL);
		intent.setData(Uri.parse("tel:" + phoneNumber));
		context.startActivity(intent);
	}

}
